package com.handpay.zztong.hp.webpay.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.Bill;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.HttpUrlConstant;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.paymentbill.activity.TransResultFailureActivity;
import com.handpay.zztong.hp.paymentbill.activity.TransResultSuccessActivity;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.webpay.model.AccountTransfer;
import com.handpay.zztong.hp.swiper.activity.VPOSActivity;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.webpay.model.WebPayModel;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

/**
 * @author yanglun E-mail:sunshine_yangl@sina.com
 * @version 2016-3-10 下午1:39:26
 */
public class WebPayWaitingResultActivity extends ZZTongActivity {

    private double amount;
    private int mPayType;
    public static final String billvalue = "bill";

    private ImageView mLoadingView;

    private WebPayModel payModel;
    LinearLayout root_layout,linear_parent=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_wating_result);
        super.onCreate(savedInstanceState);
        root_layout=(LinearLayout) findViewById(R.id.root_layout);
        linear_parent=(LinearLayout)findViewById(R.id.linear_parent);
        //主要为了防止返回后显示页面，不好--默认透明和隐藏内容
        root_layout.setBackgroundColor(Color.TRANSPARENT);
        linear_parent.setVisibility(View.INVISIBLE);

        amount = this.getIntent().getDoubleExtra(VPOSActivity.Transfer_Amount_Key, 0d);
        mPayType = this.getIntent().getIntExtra(PAYTYPE, 0);
        TextView shop_name_tv = (TextView) this.findViewById(R.id.shop_name_tv);
        goToCaptureActivity();
        TextView amount_tv = (TextView) this.findViewById(R.id.amount_tv);
        shop_name_tv.setText(AccountUtils.getShopName(this));
        this.mAction = getIntent().getByteExtra(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
        amount_tv.setText(String.format("%s元", CommonUtils.formatMoney(amount / 100d)));
        mLoadingView = (ImageView) findViewById(R.id.iv_loading);
        Animation rotateAnimation = AnimationUtils.loadAnimation(this, R.anim.iv_rotate_anim);
        mLoadingView.setAnimation(rotateAnimation);
        mLoadingView.startAnimation(rotateAnimation);
        payModel = new WebPayModel();
    }

    @Override
    protected void onResume() {
        amount = this.getIntent().getDoubleExtra(VPOSActivity.Transfer_Amount_Key, 0d);
        super.onResume();
    }

    protected void goToCaptureActivity() {
        // 打开扫描界面扫描条形码或二维码
        Intent openCameraIntent = new Intent(this, CaptureActivity.class);
        openCameraIntent.putExtra(VPOSActivity.Transfer_Amount_Key, amount);
        openCameraIntent.putExtra(PAYTYPE, mPayType);
//        openCameraIntent.putExtra("isOpenWechatPayScan", getIntent().getBooleanExtra("isOpenWechatPayScan", false));
        startActivityForResult(openCameraIntent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        HPLog.i(HPLog.LFP_TAG,"-----");
        if (resultCode == RESULT_OK) {
            if(root_layout!=null){
                root_layout.setBackgroundColor(ContextCompat.getColor(this,R.color.colorPrimary));
            }
            if(linear_parent!=null){
                linear_parent.setVisibility(View.VISIBLE);
            }
            String qrCode = data.getStringExtra("result");
            doWalletAccountTransfer(qrCode);
        } else {

            this.finish();
        }
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(getString(R.string.wating_result_title), false);
    }

    /***
     * 扫描支付宝二维码
     *
     * @param qrCode 二维码内容
     */
    private void doWalletAccountTransfer(String qrCode) {
        Hashtable<String, String> params = new Hashtable<>();
        params.put("amount", SecureManager.getInstance().des(BigDecimal.valueOf(amount).toPlainString(), 1, null));
        params.put("qrCode", SecureManager.getInstance().des(qrCode + "", 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
//        params.put("tradeType", String.valueOf(mPayType));//扫码支付不传支付方式
        params.put("clientVersion", "v" + ClientEngine.VERSION);
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        HPLog.d(HPLog.SSX_TAG, "反扫交易获取的地理位置：" + latitude.toString() + "," + longtitude.toString());
        params.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
        params.put(BaseProtocolKey.KEY_ADDRESS, address);
        params.put("requestTime", getTimeStimp());//时间戳防止网络请求出现重连机制
//        doJsonPost(true,this, ZZTongActivity.Do_WalletAccountTransfer, AccountTransfer.class, params, false);
        payModel.doWalletAccountTransfer(this, params, new BusinessEngineListener<Bill>() {
            @Override
            public void callbackBusinessResponse(Bill bill) {
                if (bill.getStatus() == 0 || bill.getStatus() == 2) {
                    Intent intent = new Intent(WebPayWaitingResultActivity.this, TransResultFailureActivity.class);
                    intent.putExtra(billvalue, bill);
                    intent.putExtra(PAYTYPE, mPayType);//传递支付方式到结果页面
                    intent.putExtra(ACTION, Action_WebPay);
                    startActivity(intent);
                    WebPayWaitingResultActivity.this.setResult(0);
                    WebPayWaitingResultActivity.this.finish();
                } else if (bill.getStatus() == 1) {
                    Intent intent = new Intent(WebPayWaitingResultActivity.this, TransResultSuccessActivity.class);
                    intent.putExtra(billvalue, bill);//传递账单到结果界面
                    intent.putExtra(PAYTYPE, mPayType);////传递支付方式到结果页面
                    intent.putExtra(ACTION, Action_WebPay);
                    startActivity(intent);
                    WebPayWaitingResultActivity.this.setResult(1);
                    WebPayWaitingResultActivity.this.finish();
                }
            }
        });
    }

    /***
     *
     * @return 获取时间戳
     */
    public static String getTimeStimp() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        return formatter.format(currentTime);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode != KeyEvent.KEYCODE_BACK && super.onKeyDown(keyCode, event);
    }
}
